<template>
  <div>
    <!-- 头部导航 -->
		<Header title="商品详情"></Header>
    <!-- 详细内容 -->
    <div class="goods-item">
      <!-- 轮播 -->
      <van-swipe
        class="my-swipe"
        :autoplay="2000"
        indicator-color="white"
        style="width: 100%;margin-top: 45px;"
      >
        <van-swipe-item v-for="(img,index) in details.imgs" :key="index">
          <img :src="img" width="100%" />
        </van-swipe-item>
      </van-swipe>
      <!-- 商品title -->
      <h4>{{details.title}}</h4>
      <!-- 商品原价 -->
      <p>
        <small>
          <s>原￥{{details.originalPrice}}</s>
        </small>
      </p>
      <!-- 商品券后价+领取优惠券 -->
      <p class="goods-price">券后￥{{details.actualPrice}}</p>
      <!-- 分割线 -->
      <van-divider style="background-color: #fff;" content-position="center">商品详情图</van-divider>
      <div class="goods_imgs">
        <img v-for="(url,index) in details.detailPics" :src="url" :key="index" />
      </div>
    </div>
    <!-- 底部导航 -->
    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" />
      <van-goods-action-icon icon="cart-o" text="购物车" :badge="cart.length" @click="goCart" />
      <van-goods-action-button type="warning" text="加入购物车" @click="addCart(details)" />
      <van-goods-action-button type="danger" text="立即购买" />
    </van-goods-action>
  </div>
</template>

<script>
import Header from "../components/Header"
export default {
  components:{
    Header
  },
  data() {
    return {
      cart: []
    };
  },
  mounted() {
    let id = this.$route.query.id;
    // console.log(id);
    this.$store.dispatch("getDetailsList", id);
    //初始化购物车
    let cart = localStorage.cart;
    if (cart != undefined) {
      this.cart = JSON.parse(cart);
    }
  },
  computed: {
    details: function() {
      return this.$store.state.detailsModule.detailsItems;
    }
  },
  methods: {
    addCart(item) {
      //添加商品
      //1.判断商品重复添加
      let isFirst = true; //是否为第一次添加，默认为true
      this.cart.map(i => {
        if (i.goods.id ==item.id) {
          i.num++;
          isFirst = false;
          return;
        }
      });

      //2.商品初次添加购物车
      if (isFirst) {
        let cart = {
          goods: item,
          num: 1
        };
        this.cart.push(cart);
      }

      //3.本地同步
      localStorage.cart = JSON.stringify(this.cart);
    },
    goCart() {
      //跳转到购物车页面
      this.$router.push({
        name: "cart"
      });
    }
  }
};
</script>

<style>
/* 券后价格样式 */
.goods-price {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.goods-price a {
  width: 80px;
  text-align: center;
  border: 1px solid #999;
  border-radius: 10px;
  color: purple;
}

/* 详细内容 */
.goods-item {
  width: 100%;
  margin-top: 50px;
  margin-bottom: 50px;
}

/* 详情图片 */
.goods_imgs {
  width: 100%;
}

.goods_imgs img {
  width: 100% !important;
  height: 100% !important;
}
</style>